package com.oop.fanxing;

import java.util.ArrayList;
import java.util.Iterator;

public class o2 {
    public static void main(String[] args) {

        //1、当我们ArrayList<Dog>表示 ArrayList 集合中存放的元素只能是Dog类型！
        //!!!!!注意 ArrayList<Dog>  和  Dog<String> 这两个分别的作用
        ArrayList<Dog> arrayList = new ArrayList<Dog>();
        arrayList.add(new Dog<String>("小白"));
        arrayList.add(new Dog<String>("小黄"));
        arrayList.add(new Dog<String>("小黑"));

        //2、如果编译器发现添加的类型，不是Dog类型，就会报错
        //arrayList.add(new Cat(10));

        //3、在遍历的时候，可以直接取出 Dog 类型而不是Objrct
        for (Dog dog : arrayList){
           System.out.println(dog.getName());
        }
        //for (Object o : arrayList){
        //   Dog dog = (Dog) o;  //原先还要向下转型Object -> Dog
        //   System.out.println(dog.getName());
        //}

        //不是说可以直接取出 Dog 类型而不是Objrct，为什么用迭代器把Object改成Dog不行，还是要强制转换
        //Iterator iterator = arrayList.iterator();
        //while (iterator.hasNext()) {
        //    Dog obj = iterator.next();
        //    System.out.println(obj);
        //}
        Iterator iterator1 = arrayList.iterator();
        while (iterator1.hasNext()) {
            Dog obj = (Dog)iterator1.next();//向下转换 强制转型
            System.out.println(obj.toString());
        }

    }
}

class Dog<E>{
    E name;
    public Dog(E name){
        this.name = name;
    }

    public E getName() {
        return name;
    }

    public void setName(E name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "name=" + name +
                '}';
    }
}

class Cat<T>{
    public Cat(T c){
        System.out.println(c);
    }
}
